/**
 * Created by Anson on 2015/1/8.
 */

MY.namespace('MY.public');
MY.public = {
    init: function(options) {
        var self = this;
        this.setting = {
            err: "",
            func: null,
            beforeClose: null, //关闭前的回调，参数为 function(tabid,closecb)，closecb的参数为tabid。即如果需要关闭，则回调closecb(tabid)
            addTabType: 'renew' //renew | active。renew是替换新页面，active为激活对应tab
        };
        $.extend(this.setting, options || {});
        setTimeout(function() {
            if (self.setting.err)
                if (self.setting.func)
                    self.message(self.setting.err, self.setting.func);
                else
                    self.message(self.setting.err);
            else if (typeof self.setting.func == "function")
                (self.setting.func)();
        }, 150); //通过定时器，防止window未加载
    },
    blockUIDo: function(options) {
        var setting = {
            message: 'loading...',
            onBlock: function(obj) {},
            onUnblock: function(obj) {}
        };
        $.extend(setting, options);

        var obj = $(setting.message);
        if (!obj.width()) {
            $("body").append("<div id=\"tempDiv\">" + setting.message + "</div>");
            obj = $("#tempDiv").children();
        }
        var width = setting.width || obj.width();
        var height = setting.height || obj.height();
        var top = ($(window).height() - height) / 2;
        top = top < 0 ? 5 : top;
        var left = ($(window).width() - width) / 2;
        $("#tempDiv").remove();
        obj == $(setting.message);
        $.blockUI({
            message: obj,
            css: {
                width: width + 'px',
                height: height + 'px',
                border: 'none',
                backgroundColor: 'transparent',
                cursor: 'default',
                top: top + 'px',
                left: left + 'px'

            },
            overlayCSS: {
                cursor: 'default',
                opacity: 0.3
            },
            onBlock: function() {
                $(setting.close, obj).click(function() {
                    $.unblockUI();
                });
                setting.onBlock(obj);
            },
            onUnblock: function() {
                $(setting.close, obj).unbind();
                setting.onUnblock(obj);
            }
        });
    },
    message: function(value, cb) {
        var self = this;
        self.blockUIDo({
            message: '<div class="massage" style="width:300px; border-radius: 4px;' +
                'border-width: 1px;padding:5px;border-style: solid;background-color: #fff;">' +
                '<p class="loadMsg" style="font-weight: 900;">提示</p>' + '<div style="padding: 0px 15px;white-space:normal;word-break:break-all;overflow:auto;">' + value +
                '<div style="margin-top:12px; ">' +
                '<button type="button" class="massageClose" class="btn btn-default" ' +
                ' style="width: 100px;font-weight: 700;">确定</button>' +
                '</div></div>',
            close: '.massageClose',
            onUnblock: cb
        });
    },
    messageYesOrNo: function(value, yesCb, noCb) {
        var self = this;
        self.blockUIDo({
            message: '<div class="massage" style="width:300px; border-radius: 4px;' +
                'border-width: 1px;padding:5px;border-style: solid;background-color: #fff;">' +
                '<p class="loadMsg" style="font-weight: 900;">提示</p>' + '<div style="padding: 0px 15px;white-space:normal;word-break:break-all;overflow:auto;">' + value +
                '<div style="margin-top:12px; ">' +
                '<button type="button" class="messageYes" class="btn btn-default" ' +
                ' style="width: 100px;font-weight: 350;">确定</button>' +
                '<button type="button" class="massageClose" class="btn btn-default" ' +
                ' style="width: 100px;font-weight: 350;">取消</button>' +
                '</div></div>',
            onBlock: function() {
                $('.massageClose').on("click", function() {
                    noCb();
                    $('.massageClose,.messageYes').off("click");
                    $.unblockUI();
                });
                $('.messageYes').on("click", function() {
                    yesCb();
                    $('.massageClose,.messageYes').off("click");
                    $.unblockUI();
                })
            }
        });
    },
    detailShow: function(value, cb) {
        var self = this;
        self.blockUIDo({
            message: '<div class="massage" style="max-height: 600px;overflow-y: auto; border-radius: 4px;' +
                'border-width: 1px;padding:5px;border-style: solid;background-color: #fff;position: relative;">' +
                '<b class="close"  style="position: absolute;top:5px;right: 5px;"><span class="glyphicon glyphicon-remove"></span></b>' + '<div style="padding:15px;text-align: left;">' + value +
                '</div>',
            width: 500,
            height: 800,
            close: '.close',
            onBlock: function() {
                $(document).on("keydown", function(event) {
                    if (event.keyCode == 27)
                        $.unblockUI();
                });
            },
            onUnblock: function() {
                $(document).off("keydown");
            }
        });
    },
    loading:function(){
        var self=this;
        self.blockUIDo({
                    message: '<div class="com_loading"' + ' style="width:200px; border-radius: 4px;border-width: 1px;padding:5px;border-style: solid;background-color: #fff;">' +
                        '<p class="loadMsg" style="margin: 5px;0px;2px;0px;">玩命处理中，请您稍等...</p>' +
                        '<div><img src="/images/loading.gif" /></div>' +
                        '</div>'
                });
    },
    ajax: function(options) {
        var self = this;
        var setting = {
            json: true,
            timeout: 60000,
            beforeSend: function() {
                self.loading();
            },
            error: function(a, b, e) {
                self.message('网络异常,请刷新页面后重新操作');
            }
        };
        $.extend(setting, options);

        if (setting.json) {
            setting.type = "POST";
            setting.contentType = 'application/json; charset=utf-8';
            setting.dataType = 'json';
            setting.data = typeof setting.data === 'string' ? setting.data : JSON.stringify(setting.data);
        }
        $.ajax(setting);
    },
    arrayGrep: function(array, func, isOne, getNum) {
        var newArray = [];
        for (var i = 0, len = array.length; i < len; i++) {
            if (func(i, array[i])) {
                if (isOne)
                    return array[i];
                newArray.push(array[i]);
                if (getNum && newArray.length == getNum)
                    return newArray;
            }
        }
        if (isOne) return null;
        return newArray;
    },
    calculate: function(formula, price, keepSingleDigit) {
        var self = this;
        if (!formula) return self.ceilPrice(price);
        if (formula.length === 1) return self.ceilPrice(price);
        if (!price && price !== 0) return null;
        price = Number(price);
        var f = formula.charAt(0);
        var l = formula.charAt(formula.length - 1);
        var indexLast = formula.length;
        if (l == '%')
            indexLast = formula.length - 1;
        var v = formula.substring(1, indexLast);
        v = parseFloat(v);
        var value = 0;
        if (l == '%') {
            value = v / 100.0 * price;
        } else
            value = v;
        if (f == '+')
            value = price + value;
        else if (f == '-')
            value = price - value;
        return self.ceilPrice(value, keepSingleDigit);
    },
    ceilPrice: function(value, keepSingleDigit) {
        if (value == null) return null;
        if (keepSingleDigit) return Math.ceil(value);
        return Math.ceil(value / 10) * 10;
    },
    initExchangeRate: function(func,disableUnBlock) {
        var self = my.public;
        self.ajax({
            url: '/basicData/currencyRate/i',
            data: null,
            success: function(data, textStatus, xhr) {
                if (!disableUnBlock) $.unblockUI();
                if (data.Code != '20000' || data.Detail.length < 1) {
                    self.message('无法查询到币种信息，请联系管理员。<br/>' + data.description);
                    func(null, null);
                    return;
                }
                var currencyList = data.Detail;
                currencyList.sort(function(a, b) {
                    return a.CurrencyCode > b.CurrencyCode ? 1 : -1;
                });
                var html = [];
                $.each(currencyList,function(i,data) {
                    if (data.CurrencyCode != 'CNY') {
                        html.push('<option value="' + data.CurrencyCode + '" exchRate="' + data.ExchRate + '">' +
                            data.CurrencyCode + '-' + data.CurrencyName_cn + ('(') + data.ExchRate + (')') +
                            '</option>');
                    }
                });
                func(currencyList, html.join(''));
            }
        });
    }
};

